import React, { Fragment } from 'react'
import { Button, Form, Icon, Input } from 'antd'
import { connect } from 'dva'
import { LangButton } from 'components/Button'

@connect(({ global, login }) => ({
  global,
  login,
}))
@Form.create()
class LoginForm extends React.Component {
  handleSubmit = (e) => {
    e.preventDefault()
    this.props.form.validateFields((err, values) => {
      if (!err) {
        this.props.dispatch({
          type: 'login/login',
          payload: values,
        })
      }
    })
  }

  handleChangeLanguage = (language) => {
    localStorage.setItem('language', language)
    this.props.dispatch({
      type: 'global/saveLanguage',
      payload: language,
    })
  }

  render() {
    const { getFieldDecorator } = this.props.form
    const { status } = this.props.login
    const { language } = this.props.global
    const usernameOrPasswordError = /error/.test(status) ? 'UserName or Password incorrect!' : ''

    return (
      <Fragment>
        <div style={{ textAlign: 'right' }}>
          <LangButton language={language} onChangeLanguage={this.handleChangeLanguage} />
        </div>
        <Form onSubmit={this.handleSubmit} className="login-form">
          <Form.Item>
            {getFieldDecorator('userName', {
              rules: [{ required: true, message: 'Please input your username!' }],
            })(
              <Input prefix={<Icon type="user" style={{ color: 'rgba(0,0,0,.25)' }} />} placeholder="Username" />
            )}
          </Form.Item>
          <Form.Item>
            {getFieldDecorator('password', {
              rules: [
                { required: true, message: 'Please input your Password!' },
              ],
            })(
              <Input
                prefix={<Icon type="lock" style={{ color: 'rgba(0,0,0,.25)' }} />}
                type="password"
                placeholder="Password"
              />
            )}
          </Form.Item>
          <div style={{ color: 'red' }}>{usernameOrPasswordError}</div>
          <Form.Item>
            <Button type="primary" htmlType="submit" style={{ width: '100%' }}>
            Log in
            </Button>
          </Form.Item>
        </Form>
      </Fragment>
    )
  }
}

export default LoginForm
